﻿/******************************************************************************
 * 创建者：gtts
 * 创建日期：2011.4.6
 * 类名：Utility
 * 说明：常用方法（工具类）
 ******************************************************************************/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Text.RegularExpressions;

namespace GTTSOfLibrary.Common
{
    /// <summary>
    /// 常用方法
    /// </summary>
    public class Usual
    {
        #region 检查字符类型

        /// <summary>
        /// 检查是否为空
        /// </summary>
        /// <param name="obj">要检查的对象或值</param>
        /// <returns></returns>
        public static bool IsNull(object obj)
        {
            if ((obj != null) && !Convert.IsDBNull(obj))
            {
                return false;
            }
            return true;
        }
        /// <summary>
        /// 检查是否为Guid类型的字符串
        /// </summary>
        /// <param name="o">要检查的字符串</param>
        /// <returns>如果是，则返回true，如果不是，则返回false</returns>
        public static bool IsGuid(object o)
        {
            try
            {
                Guid a = new Guid(o.ToString());

                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 检查是否为整数的字符串
        /// </summary>
        /// <param name="o">要检查的字符串</param>
        /// <returns>如果是，则返回true，如果不是，则返回false</returns>
        public static bool IsInt(object o)
        {
            try
            {
                Convert.ToInt32(o);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 检查是否为日期型的字符串
        /// </summary>
        /// <param name="o">要检查的字符串</param>
        /// <returns>如果是，则返回true，如果不是，则返回false</returns>
        public static bool IsDateTime(object o)
        {
            if (o == null) return false;
            try
            {
                Convert.ToDateTime(o);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 检查是否为浮点型
        /// </summary>
        /// <param name="o">要检查的字符串</param>
        /// <returns>如果是，则返回true，如果不是，则返回false</returns>
        public static bool IsDouble(object o)
        {
            double num1 = 0d;
            if (IsNull(o))
            {
                return false;
            }
            if (!double.TryParse(o.ToString(), NumberStyles.Any, null, out num1))
            {
                return false;
            }
            return true;
        }
        /// <summary>
        ///  检查是否为Single型
        /// </summary>
        /// <param name="o">要检查的字符串</param>
        /// <returns>如果是，则返回true，如果不是，则返回false</returns>
        public static bool IsSingle(object o)
        {
            try
            {
                Convert.ToSingle(o);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 检查是否为Decimal型
        /// </summary>
        /// <param name="o">要检查的字符串</param>
        /// <returns>如果是，则返回true，如果不是，则返回false</returns>
        public static bool IsDecimal(object o)
        {
            try
            {
                Convert.ToDecimal(o);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 检查是否为bool型
        /// </summary>
        /// <param name="o">要检查的字符串</param>
        /// <returns>如果是，则返回true，如果不是，则返回false</returns>
        public static bool IsBool(object o)
        {
            try
            {
                Convert.ToBoolean(o);
                return true;
            }
            catch
            {
                return false;
            }
        }

        #endregion

        #region 格式化字符串
        //TODO:格式化字符串(不太明白)
        private static string EncodeString(object theValue)
        {
            return String.Format("{0}", theValue.ToString().Replace("'", "\""));
        }

        public static object ToString(string str)
        {
            return ToString(str, DBNull.Value);
        }
        public static object ToString(string str, object defaultValue)
        {
            str = str.Trim();
            if (defaultValue != DBNull.Value)
            {
                defaultValue = IsNull(defaultValue) ? defaultValue : DBNull.Value;
            }

            if (string.IsNullOrEmpty(str))
            {
                return defaultValue;
            }
            else
            {
                return EncodeString(str);
            }
        }

        /// <summary>
        /// 去除空格
        /// </summary>
        /// <param name="str">要变换的字符串</param>
        /// <param name="removespace">是否移除空格</param>
        /// <returns></returns>
        public static object ToString(string str, bool removespace)
        {
            if (removespace)
            {
                return ToString(str.Replace(" ", ""), DBNull.Value);
            }
            else
            {
                return ToString(str, DBNull.Value);
            }
        }

        #endregion

        #region 常用类型的转换
        public static int GetInt(object obj)
        {
            return GetInt(obj, int.MinValue);
        }

        public static int GetInt(object obj, int defaultValue)
        {
            if (IsNull(obj) || !IsInt(obj))
            {
                return defaultValue;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }


        public static object ToInt(string str)
        {
            return ToInt(str, DBNull.Value);
        }

        public static object ToInt(string str, object defaultValue)
        {
            if (defaultValue != DBNull.Value)
            {
                defaultValue = IsInt(defaultValue) ? defaultValue : DBNull.Value;
            }

            if (IsNull(str) || !IsInt(str.Trim()))
            {
                return defaultValue;
            }
            else
            {
                return Convert.ToInt32(str.Trim());
            }
        }



        public static decimal GetDecimal(object obj)
        {
            return GetDecimal(obj, decimal.MinValue);
        }

        public static decimal GetDecimal(object obj, decimal defaultValue)
        {
            string str = obj as string;
            if (str != null)
            {
                //这是把$等符号去掉.
                if (str.Length > 0)
                {
                    if (str[0] > '9' || str[0] < 0)
                    {
                        str = str.Substring(1, str.Length - 1);
                    }
                }
                obj = str;
            }
            if (IsNull(obj) || !IsDecimal(obj))
            {
                return defaultValue;
            }
            else
            {
                return Convert.ToDecimal(obj);
            }
        }


        public static object ToDecimal(string str)
        {
            return ToDecimal(str, DBNull.Value);
        }

        public static object ToDecimal(string str, object defaultValue)
        {
            //这是把$等符号去掉.
            if (str.Length > 0)
            {
                if (str[0] > '9' || str[0] < 0)
                {
                    str = str.Substring(1, str.Length - 1);
                }
            }

            if (defaultValue != DBNull.Value)
            {
                defaultValue = IsDecimal(defaultValue) ? defaultValue : DBNull.Value;
            }

            if (IsNull(str) || !IsDecimal(str.Trim()))
            {
                return defaultValue;
            }
            else
            {
                return Convert.ToDecimal(str.Trim());
            }
        }



        public static double GetDouble(object obj)
        {
            return GetDouble(obj, double.NaN);
        }

        public static double GetDouble(object obj, double defaultValue)
        {
            string str = obj as string;
            if (str != null)
            {
                //这是把$等符号去掉.
                if (str.Length > 0)
                {
                    if (str[0] > '9' || str[0] < 0)
                    {
                        str = str.Substring(1, str.Length - 1);
                    }
                }
                obj = str;
            }

            if (IsNull(obj) || !IsDouble(obj))
            {
                return defaultValue;
            }
            else
            {
                return Convert.ToDouble(obj);
            }
        }


        public static object ToDouble(string str)
        {
            return ToDouble(str, DBNull.Value);
        }

        public static object ToDouble(string str, object defaultValue)
        {

            if (str.Length > 0)
            {
                if (str[0] > '9' || str[0] < 0)
                {
                    str = str.Substring(1, str.Length - 1);
                }
            }

            if (defaultValue != DBNull.Value)
            {
                defaultValue = IsDouble(defaultValue) ? defaultValue : DBNull.Value;
            }

            if (IsNull(str) || !IsDouble(str.Trim()))
            {
                return defaultValue;
            }
            else
            {
                return Convert.ToDouble(str.Trim());
            }
        }


        public static string GetString(object obj)
        {
            return GetString(obj, string.Empty);
        }
        public static string GetString(object obj, string defaultValue)
        {
            if (!IsNull(obj))
            {
                return obj.ToString();
            }
            else
            {
                return defaultValue;
            }
        }
        public static Guid GetGuid(object obj)
        {
            return GetGuid(obj, Guid.Empty);
        }

        public static Guid GetGuid(object obj, Guid defaultValue)
        {
            if (IsNull(obj) || !IsGuid(obj))
            {
                return defaultValue;
            }
            else
            {
                return new Guid(obj.ToString());
            }
        }

        public static object ToGuid(object str)
        {
            if (str == null)
            {
                return ToGuid(null, DBNull.Value);
            }
            else
            {
                return ToGuid(str.ToString(), DBNull.Value);
            }
        }

        public static object ToGuid(string str)
        {
            return ToGuid(str, DBNull.Value);
        }

        public static object ToGuid(string str, object defaultValue)
        {
            if (defaultValue != DBNull.Value)
            {
                defaultValue = IsGuid(defaultValue) ? defaultValue : DBNull.Value;
            }

            if (IsNull(str) || !IsGuid(str.Trim()))
            {
                return defaultValue;
            }
            else
            {
                return new Guid(str.Trim());
            }
        }




        public static bool GetBool(object obj)
        {
            return GetBool(obj, false);
        }

        public static bool GetBool(object obj, bool defaultValue)
        {
            if (IsNull(obj) || !IsBool(obj))
            {
                return defaultValue;
            }
            else
            {
                return Convert.ToBoolean(obj);
            }

        }


        public static object ToBool(string str)
        {
            return ToBool(str, DBNull.Value);
        }

        public static object ToBool(string str, object defaultValue)
        {
            if (defaultValue != DBNull.Value)
            {
                defaultValue = IsBool(defaultValue) ? defaultValue : DBNull.Value;
            }

            if (str == null || str.Trim() == string.Empty)
            {
                return defaultValue;
            }
            else
            {
                string str1 = str.ToLower().Trim();
                if (str1 == "1" || str1 == "true")
                {
                    return true;
                }
                else if (str1 == "0" || str1 == "false")
                {
                    return false;
                }
                else
                {
                    return defaultValue;
                }
            }
        }


        public static DateTime GetDateTime(object obj)
        {
            return GetDateTime(obj, DateTime.Now);
        }

        public static DateTime GetDateTime(object obj, DateTime defaultValue)
        {
            if (IsNull(obj) || !IsDateTime(obj))
            {
                return defaultValue;
            }
            else
            {
                return Convert.ToDateTime(obj);
            }
        }


        public static object ToDateTime(string str)
        {
            return ToDateTime(str, DBNull.Value);
        }

        public static object ToDateTime(string str, object defaultValue)
        {
            if (defaultValue != DBNull.Value)
            {
                defaultValue = IsDateTime(defaultValue) ? defaultValue : DBNull.Value;
            }

            if (IsNull(str) || !IsDateTime(str.Trim()))
            {
                return defaultValue;
            }
            else
            {

                return Convert.ToDateTime(str.Trim()).ToUniversalTime();
            }
        }

        public static object ToDateTime(object date, object time)
        {
            return ToDateTime(date, time, DBNull.Value);
        }

        public static object ToDateTime(object date, object time, object defaultValue)
        {
            if (defaultValue != DBNull.Value)
            {
                defaultValue = IsDateTime(defaultValue) ? defaultValue : DBNull.Value;
            }

            if (IsNull(date) || !IsDateTime(date))
            {
                return defaultValue;
            }

            string selectTime = time == null || time.ToString().Trim() == string.Empty ? "12:00 PM" : time.ToString().Trim();

            DateTime dateTime1 = Convert.ToDateTime(date.ToString().Trim());

            return Convert.ToDateTime(dateTime1.ToShortDateString() + " " + selectTime).ToUniversalTime();
        }

        private static byte[] ToBytes(string str)
        {
            return Encoding.UTF8.GetBytes(str);
        }

        #endregion

        #region 序列化
        /// <summary>
        /// 序列化一个对象，把一个对象序列化成一个字符串
        /// </summary>
        /// <param name="obj">对象</param>
        /// <returns>序列化好的字符串</returns>
        public static string SerializeObject(object obj)
        {
            XmlDocument document1 = new XmlDocument();
            using (MemoryStream stream1 = new MemoryStream())
            {
                using (StreamWriter writer1 = new StreamWriter(stream1, Encoding.Unicode))
                {
                    try
                    {
                        new XmlSerializer(obj.GetType()).Serialize(stream1, obj);
                    }
                    catch
                    {
                        if (!(obj is Exception))
                        {
                            throw;
                        }
                        return ((Exception)obj).ToString();
                    }
                    stream1.Seek((long)0, SeekOrigin.Begin);
                    document1.Load(stream1);
                    return document1.DocumentElement.OuterXml;
                }
            }
        }

        /// <summary>
        /// 序列化一个对象数组，把一个对象数组序列化成一个字符串
        /// </summary>
        /// <param name="arr">对象数组</param>
        /// <returns>序列化好的字符串</returns>
        public static string SerializeObjectArray(object[] arr)
        {
            StringBuilder builder1 = new StringBuilder();
            builder1.Append("<details> ");
            object[] objArray1 = arr;
            for (int num1 = 0; num1 < objArray1.Length; num1++)
            {
                object obj1 = objArray1[num1];
                builder1.Append(SerializeObject(obj1));
            }
            builder1.Append(" </details>");
            XmlDocument document1 = new XmlDocument();
            document1.LoadXml(builder1.ToString());
            return document1.OuterXml;
        }
        #endregion

        #region 货币金额
        /// <summary>
        /// 把货币金额转成英文的大写．
        /// </summary>
        /// <param name="sAmount">要转换大写的货币金额</param>
        /// <param name="bShowSuffix">是否要显示小数点后面的同容</param>
        /// <returns>格式好的字符串</returns>
        public static string GetAmountEnglisth(string sAmount, bool bShowSuffix)
        {
            string[] numAry = "One,Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten,Eleven,Twelve,Thirteen,Fourteen,Fifteen,Sixteen,Seventeen,Eighteen,Nineteen".Split(',');
            string[] num10Ary = "Ten,Twenty,Thirty,Forty,Fifty,Sixty,Seventy,Eighty,Ninety".Split(',');
            string[] carrySymbolAry = "Hundred,Thousand,Million,Billion".Split(',');


            decimal d = Convert.ToDecimal(sAmount);
            if (d > 100000000000) return "";
            string sValue = d.ToString("#0");
            string sInt = "";
            string sDec = "";
            if (bShowSuffix)
            {
                sValue = d.ToString("#0.00");
                int iZeroPos = sValue.IndexOf(".");
                sInt = sValue.Substring(0, iZeroPos);
                sDec = sValue.Substring(iZeroPos + 1);
            }
            else
            {
                sInt = sValue;
            }

            if (sInt.Length > 11)
            {
                return "can not translate so big number!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!";
            }

            System.Text.StringBuilder sbRes = new System.Text.StringBuilder();
            for (int i = 0; i < sInt.Length; i++)
            {
                int iPos = sInt.Length - i;
                int iCarryPos = iPos % 3;

                int num = Convert.ToInt32(sInt.Substring(i, 1));
                if (num == 0)
                {

                    if (iCarryPos == 2)
                    {
                        sbRes.Append(" and");
                    }

                    if (iPos == 4 || iPos == 7 || iPos == 10)
                    {
                        int iSectionPos = (int)Math.Floor(Convert.ToDecimal(iPos / 3));
                        sbRes.Append(" " + carrySymbolAry[iSectionPos]);
                    }


                    continue;
                }

                if (iCarryPos == 0)
                {
                    sbRes.Append(" " + numAry[num - 1] + " Hundred");
                }
                else if (iCarryPos == 2)
                {
                    if (sbRes.Length > 7)
                    {

                        sbRes.Append(" and");

                    }
                    if (num == 1) // evelven twelve etc..
                    {
                        i++;
                        int numNext = Convert.ToInt32(sInt.Substring(i, 1));
                        num = num * 10 + numNext;
                        sbRes.Append(" " + numAry[num - 1]);
                        iPos = sInt.Length - i; //Recalculate iPos;
                    }
                    else
                    {
                        sbRes.Append(" " + num10Ary[num - 1]);
                    }


                }
                else if (iCarryPos == 1)
                {
                    if (sbRes.Length > 0)
                    {
                        if (sbRes.ToString().Substring(sbRes.Length - 2, 2) == "ty")
                        {
                            sbRes.Append(" ");
                        }
                    }
                    sbRes.Append(" " + numAry[num - 1]);
                }


                if (iPos == 4 || iPos == 7 || iPos == 10)
                {
                    int iSectionPos = (int)Math.Floor(Convert.ToDecimal(iPos / 3));
                    sbRes.Append(" " + carrySymbolAry[iSectionPos]);
                }
            }

            string res = sbRes.ToString();
            while (res.IndexOf(" and and") > -1)
            {
                res = res.Replace(" and and", " and");
            }
            res = res.Trim();
            while (res.Length > 3 && res.Substring(res.Length - 3, 3) == "and")
            {
                res = res.Substring(0, res.Length - 3);
            }
            res = res.Replace("- ", "-");


            res = res.Replace(" and Thousand", " Thousand");
            res = res.Replace(" and Million", " Million");
            res = res.Replace(" and Billion", " Billion");

            res = res.Replace("Million Thousand", "Million");
            res = res.Replace("Billion Million", "Billion");


            if (bShowSuffix)
            {

                int iCents = Convert.ToInt32(sDec);
                if (iCents > 0)
                {
                    res += " and";
                    if (iCents < 20)
                    {
                        res += " " + numAry[iCents - 1];
                    }
                    else
                    {
                        res += " " + num10Ary[Convert.ToInt32(sDec.Substring(0, 1)) - 1];
                        if (sDec.Substring(1, 1) != "0")
                        {
                            res += " " + numAry[Convert.ToInt32(sDec.Substring(1, 1)) - 1];
                        }
                    }
                    res += " Cents";

                }
                else
                {
                    res += " Even";
                }
            }
            //替换多的END信息
            res = res.Replace(" and ", "|");
            if (res.IndexOf("|") < 0)
            {
                return res;
            }
            else
            {
                string[] p = res.Split(new char[] { '|' });
                if (p.Length == 2)
                {
                    return p[0] + " and " + p[1];
                }
                else
                {
                    string temp = string.Empty;
                    for (int i = 0; i < p.Length; i++)
                    {
                        if (i != p.Length - 1)
                        {
                            temp += " " + p[i];
                        }
                        else
                        {
                            temp += " and " + p[i];
                        }
                    }
                    return temp;
                }
            }


        }

        /// <summary>
        /// 把货币金额从数字转为大写
        /// </summary>
        /// <param name="sAmount">要转换大写的货币金额</param>
        /// <param name="bShowSuffix">是否要显示小数点后面的同容</param>
        /// <returns>格式好的字符串</returns>
        public static string GetAmountChinese(string sAmount, bool bShowSuffix)
        {
            string[] numAry = new string[] { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
            string[] posAry = new string[] { "", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟" };
            string[] decAry = new string[] { "角", "分" };
            try
            {
                decimal.Parse(sAmount);
            }
            catch
            {
                return "零圆";
            }

            string res = "";
            decimal d = Convert.ToDecimal(sAmount);
            string sValue = d.ToString("#0");
            string sInt = sValue;
            string sDec = "";
            int iZeroPos = 0;
            if (bShowSuffix)
            {
                sValue = d.ToString("#0.00");
                iZeroPos = sValue.IndexOf(".");
                sInt = sValue.Substring(0, iZeroPos);
                sDec = sValue.Substring(iZeroPos + 1);
            }


            if (bShowSuffix)
            {

                sInt = sValue.Substring(0, iZeroPos);
            }

            if (sInt.Length > 11)
            {
                return "can not translate so big number!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!";
            }
            for (int i = 0; i < sInt.Length; i++)
            {
                res += numAry[Convert.ToInt32(sInt.Substring(i, 1))] + posAry[sInt.Length - i - 1];
            }

            res = res.Replace("零圆", "");
            res = res.Replace("零拾", "零");
            res = res.Replace("零佰", "零");
            res = res.Replace("零仟", "零");


            while (res.IndexOf("零亿") > -1)
            {
                res = res.Replace("零亿", "亿");
            }
            while (res.IndexOf("零万") > -1)
            {
                res = res.Replace("零万", "万");
            }
            res = res.Replace("亿万", "亿");
            while (res.IndexOf("零零") > -1)
            {
                res = res.Replace("零零", "零");
            }
            if (res.Substring(res.Length - 1, 1) == "零")
            {
                res = res.Substring(0, res.Length - 1);
            }

            res += "圆";
            if (bShowSuffix)
            {
                for (int i = 0; i < sDec.Length; i++)
                {
                    res += numAry[Convert.ToInt32(sDec.Substring(i, 1))] + decAry[i];
                }

                res = res.Replace("零角零分", "整");
            }

            if (res == "圆")
            {
                res = "零圆";
            }
            return res;
        }
        #endregion

      
     
    }
}
